package com.team.RunsFast_Api.service.impl;

import com.alipay.api.domain.CountInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.RunsFast_Api.dao.CouponDao;
import com.team.RunsFast_Api.dao.CouponInfoDao;
import com.team.RunsFast_Api.dao.OrderDao;
import com.team.RunsFast_Api.dto.CouponDto;
import com.team.RunsFast_Api.dto.CouponInfoDto;
import com.team.RunsFast_Api.service.intf.CouponInfoService;
import com.team.runsfast.entity.CouponInfo;
import com.team.runsfast.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CouponInfoServiceImpl implements CouponInfoService {
    private final CouponInfoDao dao;
    private final OrderDao orderDao;
    private final CouponDao couponDao;

    public CouponInfoServiceImpl(CouponInfoDao dao, OrderDao orderDao, CouponDao couponDao) {
        this.dao = dao;
        this.orderDao = orderDao;
        this.couponDao = couponDao;
    }

    @Override
    @Transactional
    public R save(CouponInfo couponInfo) {
        if(dao.insert(new CouponInfo(couponInfo.getCoupid(),couponInfo.getUid())) > 0){
            couponDao.updateCoupon(couponInfo.getCoupid());
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public R queryAll() {
        return R.ok(dao.selectList(null));
    }

    @Override
    public List<CouponInfo> selectByUid(String token) {
        return dao.selectList(new QueryWrapper<CouponInfo>().eq("uid",Long.parseLong(token)).eq("flag",1));
    }

    //判断是否可以使用优惠券   并返回优惠后的价格
    @Override
    public R discountPrice(CouponInfoDto dto, String token) {
        long uid = Long.parseLong(token);
        if(dto != null){
                List<CouponDto> coupon = couponDao.selectByIds(dto.getCoupid());
                //订单总金额大于优惠券限制金额才能使用
            for (CouponDto coup:coupon) {
                if(dto.getPrice() >= coup.getStintmoney()){
                    double couponPrice = dto.getPrice() - coup.getDiscountprice();
                    return R.ok(couponPrice);
                }
            }
        }
        return R.fail();
    }

    @Override
    public R updateCoupon(long id) {
        if(dao.updateCouponInfo(id) > 0){
            return R.ok();
        }else {
            return R.fail();
        }
    }
}
